package com.meida.student.app.user.handler;

import com.meida.common.base.entity.EntityMap;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.mybatis.interceptor.GetInterceptor;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.security.OpenHelper;
import com.meida.common.utils.ConvertUtils;
import com.meida.common.utils.DateUtils;
import com.meida.common.utils.RedisUtils;
import com.meida.module.bus.client.entity.BusOrder;
import com.meida.module.bus.client.entity.BusSubject;
import com.meida.module.bus.client.entity.BusTutorType;
import com.meida.module.bus.client.enums.OrderStatePEnum;
import com.meida.module.bus.client.enums.OrderStateYEnum;
import com.meida.module.bus.client.enums.OrderStateZEnum;
import com.meida.module.bus.client.enums.OrderTypeEnum;
import com.meida.module.bus.provider.service.*;
import com.meida.module.bus.provider.utils.MyDateUtils;
import com.meida.module.user.client.entity.AppUser;
import com.meida.module.user.provider.service.AppUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 订单详情
 *
 * @author zyf
 */
@Component
public class BusOrderDetailHandler implements GetInterceptor {

    @Autowired
    private BusSubjectService busSubjectService;

    @Autowired
    private BusOrderAnswerService busOrderAnswerService;

    @Autowired
    private BusScholartyrantService busScholartyrantService;

    @Autowired
    private BusOrderAppraiseService busOrderAppraiseService;

    @Autowired
    private AppUserService appUserService;

    @Autowired
    private BusTutorTypeService busTutorTypeService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private HttpServletRequest httpServletRequest;


    @Override
    public void prepare(CriteriaQuery cq, EntityMap entityMap) {
        cq.clear();
        cq.select(BusOrder.class, "orderId", "coverImg", "orderNo", "answerUserId", "orderType", "userId", "orderAmount", "expectedAmount", "rewardAmount", "discountAmount", "orderState", "answerUserId", "subjectId", "subjectIds", "orderDescribe", "appointmentTime", "appointmentDate", "durationTime", "expiryTime", "payableAmount", "payState", "payTime", "payType", "tutorTypeId", "commission", "createTime", "deleted");
        cq.select(BusSubject.class, "subjectTitle");
        cq.eq(BusOrder.class, "orderId");
        cq.eq(BusOrder.class, "deleted", 0);
        cq.createJoin(BusSubject.class).setMainField("subjectId").setJoinField("subjectId");
    }

    @Override
    public void complete(CriteriaQuery cq, EntityMap map) {
        Long tutorTypeId = map.getLong("tutorTypeId");
        Integer deleted = map.getInt("deleted", 0);
        map.put("tutorTypeName", "");
        if (FlymeUtils.isNotEmpty(tutorTypeId)) {
            BusTutorType busTutorType = busTutorTypeService.getById(tutorTypeId);
            if (FlymeUtils.isNotEmpty(busTutorType)) {
                map.put("tutorTypeName", busTutorType.getTutorTypeName());
            }
        }
        Long orderId = map.getLong("orderId");
        //当前登录用户
        Long userId = OpenHelper.getUserId();
        Integer orderType = map.getInt("orderType");
        String orderState = map.get("orderState");
        //订单创建用户ID
        Long orderUserId = map.getLong("userId");
        //返回学霸信息
        Long answerUserId = map.getLong("answerUserId");
        //设置解答记录Id
        map.put("answerId", "");
        //追问状态
        Integer canReply = 0;
        //作答状态
        Integer answerState = -1;
        //作业无忧类型订单(如果未指定学霸,学霸为当前访问人,查询出价记录orderAnswer)
        if (OrderTypeEnum.HomeWork.getValue() == orderType) {
            if (FlymeUtils.isEmpty(answerUserId)) {
                answerUserId = OpenHelper.getUserId();
            }
        }
        Integer isXueBa = 1;
        //订单解答
        EntityMap orderAnswer = busOrderAnswerService.getOrderAnswerByOrderIdAndUserId(orderId, answerUserId);


        if (userId.equals(orderUserId)) {
            isXueBa = 0;
        }
        map.put("isXueBa", isXueBa);
        if (isXueBa == 1) {
            answerUserId = userId;
        }


        Integer showAnswer = 0;
        Integer receiveState = 0;
        if (FlymeUtils.isNotEmpty(orderAnswer)) {
            map.put("answerId", orderAnswer.getLong("answerId"));
            //用户还价
            map.put("bargainPrice", orderAnswer.getBigDecimal("bargainPrice"));
            //学霸报价
            map.put("quotedPrice", orderAnswer.getBigDecimal("quotedPrice"));
            answerState = orderAnswer.getInt("answerState");
            //审核通过后或者是学霸则展示答案
            if (answerState == 2 || userId.equals(answerUserId)) {
                putOrderAnswer(map, answerUserId, orderAnswer);
                showAnswer = 1;
            }
            if (answerState.equals(2) && !orderState.equals("7")) {
                canReply = 1;
            }
            EntityMap settleConfig = redisUtils.getConfigMap("SETTLE_CONFIG");
            Integer orderCanQuestionDay = settleConfig.getInt("orderCanQuestionDay");
            Date checkTime = orderAnswer.get("checkTime");
            if (FlymeUtils.isNotEmpty(checkTime)) {
                Date canQuestionDate = DateUtils.plusDateDays(checkTime, orderCanQuestionDay);
                String canQuestionDateStr = DateUtils.formatDate(canQuestionDate, "yyyy-MM-dd HH:mm:ss");
                Boolean isGt = DateUtils.gt(DateUtils.getDateTime(), canQuestionDateStr);
                if (isGt) {
                    canReply = 0;
                }
            }
            receiveState = orderAnswer.getInt("receiveState");
        }
        Integer isMyOrder = 0;
        if (orderState.equals(OrderStateYEnum.OrderState1.getValue()) || orderState.equals(OrderStateZEnum.OrderState1.getValue()) || orderState.equals(OrderStatePEnum.OrderState1.getValue())) {
            Long orderAnswerUserId = map.getLong("answerUserId");
            isMyOrder = FlymeUtils.isNotEmpty(orderAnswerUserId) ? 1 : 0;

        }
        map.put("isMyOrder", isMyOrder);
        map.put("answerState", answerState);
        map.put("receiveState", receiveState);
        Long appraiseNum = busOrderAppraiseService.countNumByOrderId(orderId);
        map.put("appraiseNum", appraiseNum);
        //格式化显示日期
        Date createTime = map.get("createTime");
        String targetTimezone = httpServletRequest.getHeader("targetTimezone");
        String showTime = DateUtils.formatFromTodayByTargetTimezone(createTime,targetTimezone);
        map.put("showTime", showTime);
        String appointmentDate = map.get("appointmentDate");
        String appointmentTime = map.get("appointmentTime");
        map.put("canReply", canReply);
        AppUser appUser = appUserService.getUserById(orderUserId);
        map.put("orderUserNickName", appUser.getNickName());
        map.put("showAnswer", showAnswer);
        if (FlymeUtils.isNotEmpty(appointmentDate)) {
            String appointmentDateTimeStr = appointmentDate + " " + appointmentTime + ":00";
            Date date = DateUtils.strToDate(appointmentDateTimeStr, "yyyy-MM-dd HH:mm:ss");
            Date newDate = MyDateUtils.convertTimezone(date,"UTC", targetTimezone);
            String newAppointmentDate = DateUtils.formatDate(newDate, "yyyy-MM-dd");
            String newAppointmentTime = DateUtils.formatDate(newDate, "HH:mm");
            String dayOfWeek = DateUtils.getDayOfWeek(DateUtils.formatDate(newAppointmentDate));
            map.put("dayOfWeek", dayOfWeek);
            map.put("appointmentDate", newAppointmentDate);
            map.put("appointmentTime", newAppointmentTime);
        }
        //是否允许删除
        Integer allowDel = 0;
        //是否允许取消订单
        Integer allowCancel = 0;
        //是否允许编辑问题描述
        Integer allowEditDesc = 0;
        //是否允许上传附件
        Integer allowUpload = 0;

        //是否允许学霸删除
        Integer allowXbDel = 0;
        if (orderState.equals("-1") || orderState.equals("5") || orderState.equals("7") || orderState.equals("0")) {
            allowDel = 1;
        }
        if (orderState.equals("P1") || orderState.equals("Z1") || orderState.equals("Y1")) {
            allowCancel = 1;
        }
        if (orderState.equals("P1") || orderState.equals("Z1") || orderState.equals("Y1") || orderState.equals("-1")) {
            allowEditDesc = 1;
        }
        if (orderState.equals("2") || orderState.equals("P1") || orderState.equals("Z1") || orderState.equals("Y1") || orderState.equals("-1")) {
            allowUpload = 1;
        }
        if (isXueBa == 1 && deleted == 1 && (orderState == "7" || orderState == "5")) {
            allowXbDel = 1;
        }
        map.put("allowDel", allowDel);
        map.put("allowEditDesc", allowEditDesc);
        map.put("allowUpload", allowUpload);
        map.put("allowCancel", allowCancel);
        map.put("allowXbDel", allowXbDel);
        map.put("liveUrl", "https://www.studentliu.com/");

        //格式化支付时间
        if (FlymeUtils.isNotEmpty(targetTimezone)) {
            String payTime = map.get("payTime");
            if (FlymeUtils.isNotEmpty(payTime)) {
                String timezonePayTime = MyDateUtils.convertTimezone(payTime, targetTimezone);
                map.put("payTime", timezonePayTime);
            }
        }

    }

    /**
     * 学霸信息
     *
     * @param map
     * @param answerUserId
     */
    private void putAnswerUserInfo(EntityMap map, Long answerUserId) {
        if (FlymeUtils.isNotEmpty(answerUserId)) {
            EntityMap answerUserInfo = busScholartyrantService.getScholartyrantInfo(answerUserId);
            String subjectIds = answerUserInfo.get("subjectInfo");
            List<String> subjectTitles = busSubjectService.selectSubjectTitles(subjectIds);
            answerUserInfo.put("subjectTitles", ConvertUtils.listToString(subjectTitles));
            map.put("answerUserInfo", answerUserInfo);
        }
    }

    /**
     * 设置订单答案
     *
     * @param map
     * @param answerUserId
     * @param orderAnswer
     */
    private void putOrderAnswer(EntityMap map, Long answerUserId, EntityMap orderAnswer) {
        if (FlymeUtils.isNotEmpty(answerUserId)) {
            if (FlymeUtils.isNotEmpty(orderAnswer)) {
                map.put("orderAnswer", orderAnswer);
            }
        }
    }

}
